package maple.core;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.Date;
import java.util.logging.Level;

import jade.lang.acl.ACLMessage;
import jade.wrapper.StaleProxyException;

import maple.lang.Command;
import maple.lang.Language;
import maple.util.Timestamp;

public class Reader extends MapleAgent
{
	private boolean _start;
	private boolean _available;

	// TODO: fill in your codes
	private String gateway = "";
	private String command = "";

	public Reader()
	{
		super();
		_start = false;
		_available = false;
	}

	protected void takeDown()
	{
		if( _available )
		{
			sendMessage( ACLMessage.REQUEST, gateway, command, null, getName() );
		}
	}

	protected void actionInform( final ACLMessage message )
	{
		System.out.println( message.getContent() );
	}

	protected void actionRequest( final ACLMessage message )
	{
		String content = message.getContent();
		if( content.equals( "start" ) )
		{
			_start = true;
			System.out.println( Timestamp.Default.format( new Date( System.currentTimeMillis() ) ) + Language.DELIMITER + getName() + " is start!" );
		}
	}

	protected boolean distribute()
	{
		if( _start )
		{
        	gateway = "PhidgetSBC_02@140.112.30.185";
			command = "READ PORT=\"A.0\" INTERVAL=\"60000\" RECEIVER=\"" + getName() + "\"";
            
			if( sendMessage( ACLMessage.REQUEST, gateway, command, null, getName() ) )
			{
				// wait for a response
				ACLMessage message = blockingReceive();
				switch( message.getPerformative() )
				{
					case ACLMessage.INFORM:
						actionInform( message );
						break;
				}
			}
			else
			{
				System.out.println( Command.Message.BAD_COMMAND.toString() );
			}

			_start = false;
			_available = true;
			return true;
		}
		else
		{
			return super.distribute();
		}
	}
}
